<%@ include file="/WEB-INF/views/commonJSTL.jsp" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>${s_UserPharmacy.pharmacy.name}</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<%@ include file="/WEB-INF/views/commonResources.jsp" %>

<script src="<c:url value="/resources/js/ui/minified/jquery.ui.core.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.ui.widget.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.ui.position.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.ui.mouse.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.ui.button.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.ui.draggable.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.ui.resizable.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.ui.datepicker.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.ui.dialog.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.effects.core.min.js" />"></script>
<script src="<c:url value="/resources/js/jquery.form.js" />"></script>
<script src="<c:url value="/resources/js/jquery-1.9.1.js" />"></script>
<script src="<c:url value="/resources/js/ui/jquery-ui.js" />"></script>
<script src="<c:url value="/resources/js/validate/jquery.validate.min.js" />"></script>

<script src="<c:url value="/resources/js/jquery.print.js" />"></script>


<fmt:message key="form.selected" var="selected"/>	
<c:set var="classTemp" value="form_align40" />


<style type="text/css"> 
.tablaBorder
{
  border-collapse: separate;
  border: solid Black 1px;
  border-spacing: 1px 1px; /* Horiz, Vert */
  background-color: Lightgrey;
} 
.col1 { width:  80px; text-align:left; }
.col2 { width: 120px; text-align:center; }
.col3 { width:  50px; text-align:right; }
 
.resumen { table-layout:fixed; }
.resumen th { font-size:11px; background-color: Silver; }
 
.todo { overflow:auto; height:100px; }
.detalle { table-layout:fixed; }
.row0 { background-color: #E7E7E7; }
.row1 { background-color: Lightgrey; }
 
 
 
/*
#mainContainerSearch tbody, #mainContainerSearch thead tr { display: block; }

#mainContainerSearch tbody {
    height: 60px;
    overflow-y: auto;
    overflow-x: hidden;
}

#mainContainerSearch tbody td, #mainContainerSearch thead th {
    width: 150px;
}

#mainContainerSearch thead th:last-child {
    width: 180px; 
}
*/


	.fieldset1 {height: 300px; padding: 10px;} 
	.legend1 {font-weight: bold;}
	.fieldset2 {height: 280px; padding: 10px;} 
	.legend2 {font-weight: bold;}
	
	.printable {border: 1px dotted #CCCCCC ;padding: 10px 10px 10px 10px ;}
	
	.myBox {margin: 0 auto;border: 0px solid #fff;color: #000;/*letra color*/height: 35px;padding: 1px;font-size: 14px; font-weight: bold; text-align: center;font-family: arial;background-color: #e5fafc;-webkit-border-radius: 8px;-moz-border-radius: 8px;vertical-align:text-bottom;}
	
	
	
	.loading {
		-webkit-border-radius: 20px;
		border-radius: 20px;
		/*
		-webkit-box-shadow:inset 1px 1px 10px 1px #0B03FF;
		box-shadow:inset 1px 1px 10px 1px #0B03FF;
		*/
		width: 98%;height: 70%;
		top: 15%;
		left: 1%;
		overflow: hidden; 
		z-index: 10000;
		text-align: center;
		position:absolute; 
		background-color: #FFFFFF;
		opacity:0.6;
		filter:alpha(opacity=40);
	}	
</style> 

<script type="text/javascript">

	var productList = [];
	var productSelected = null;
	var activeRow = null;
	
	
	var contItem = 0;
	var countPackage = 0;
	var pack = null;
	var retailItem 		= 0;
	var retailPackage 	= 0;
	var wholesaleItem 	= 0;
	var wholesalePackage= 0;
	
	
	var priceTotalList 	= [];
	var indexRow 		= 0;
	var indexRowSelected= 0;
	
	
	var packageList = [];
	var itemList 	= [];
	var productSelectedTemp = null;
	
	var arrayItemTemp	= [];
	
	/*Literal de numeros*/
	var textLiteral= '';

	var sUserId = "<c:out value="${s_UserPharmacy.userpharmacyPK.userId}"/>";
	$(function() {
	    
		  $.datepicker.regional['es'] = 
		  {
		  closeText: 'Cerrar', 
		  prevText: 'Previo', 
		  nextText: 'Próximo',
		  
		  monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio',
		  'Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
		  monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun',
		  'Jul','Ago','Sep','Oct','Nov','Dic'],
		  monthStatus: 'Ver otro mes', yearStatus: 'Ver otro año',
		  dayNames: ['Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado'],
		  dayNamesShort: ['Dom','Lun','Mar','Mie','Jue','Vie','Sáb'],
		  dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','Sa'],
		  dateFormat: 'dd/mm/yy', firstDay: 0, 
		  initStatus: 'Selecciona la fecha', isRTL: false};
		  $.datepicker.setDefaults($.datepicker.regional['es']);
	});
	
	
	
	var productListDetail = [];
	var productShowed = null;
	<c:forEach var="itemProduct" items="${listProductDetail}">
		var listCompositionTemp = [];
		<c:forEach var="itemComposition" items="${itemProduct.compositionCollection}">
			var typeCompositionTemp = {typeCompositionId:"<c:out value="${itemComposition.typeCompositionId.typeCompositionId}"/>",name:"<c:out value="${itemComposition.typeCompositionId.name}"/>"};			
			var composition 		= {detailCheckHealth:"<c:out value="${itemComposition.detailCheckHealth}"/>",checkHealth:"<c:out value="${itemComposition.checkHealth}"/>",quantity:"<c:out value="${itemComposition.quantity}"/>",valueRadio:"<c:out value="${itemComposition.valueRadio}"/>",typeComposition:typeCompositionTemp,compositionId:"<c:out value="${itemComposition.compositionId}"/>",name:"<c:out value="${itemComposition.name}"/>",quantity:"<c:out value="${itemComposition.quantity}"/>"};	
			listCompositionTemp.push(composition);
		</c:forEach>
		var listProductAttributesTemp = [];
		<c:forEach var="itemProductAttributes" items="${itemProduct.productattributesCollection}">
			var productAttributesPK = {	productAttributeId:"<c:out value="${itemProductAttributes.productattributesPK.productAttributeId}"/>",
										providerId:"<c:out value="${itemProductAttributes.productattributesPK.providerId}"/>",
										productId:"<c:out value="${itemProductAttributes.productattributesPK.productId}"/>"};
			var productAttributeTemp= {	productAttributeId:"<c:out value="${itemProductAttributes.productattribute.productAttributeId}"/>",
										name:"<c:out value="${itemProductAttributes.productattribute.name}"/>"};			
			var productTemp			= {	providerId:"<c:out value="${itemProduct.productPK.providerId}"/>",
										productId:"<c:out value="${itemProduct.productPK.productId}"/>",
										name:"<c:out value="${itemProduct.name}"/>"};			
			var productAttributesTemp	= {productAttributesPK:productAttributesPK,productAttribute:productAttributeTemp,product:productTemp};
			listProductAttributesTemp.push(productAttributesTemp);
		</c:forEach>
		
		var listAttributeTemp = [];
		<c:forEach var="itemAttribute" items="${itemProduct.activeSubstanceId.attributeCollection}">
			var attributeTemp = {attributeId:"<c:out value="${itemAttribute.attributePK.attributeId}"/>",activeSubstanceId:"<c:out value="${itemAttribute.attributePK.activeSubstanceId}"/>",name:"<c:out value="${itemAttribute.name}"/>",detail:"<c:out value="${itemAttribute.detail}"/>",order:"<c:out value="${itemAttribute.order}"/>"};			
			listAttributeTemp.push(attributeTemp);
		</c:forEach>
		
		var activeSubstanceTemp = {	activeSubstanceId:"<c:out value="${itemProduct.activeSubstanceId.activeSubstanceId}"/>",			
								therapeuticAction:"<c:out value="${itemProduct.activeSubstanceId.therapeuticAction}"/>", 
								name:"<c:out value="${itemProduct.activeSubstanceId.name}"/>", 
								attributeCollection:listAttributeTemp, 
								synonyms:"<c:out value="${itemProduct.activeSubstanceId.synonyms}"/>",
								properties:"<c:out value="${itemProduct.activeSubstanceId.properties}"/>"};
		var p = {
				generalIndication:"<c:out value="${itemProduct.generalIndication}"/>",
				presentation:"<c:out value="${itemProduct.presentation}"/>",
				providerId:"<c:out value="${itemProduct.productPK.providerId}"/>",
				productId:"<c:out value="${itemProduct.productPK.productId}"/>",
				name:"<c:out value="${itemProduct.name}"/>",
				genericName:"<c:out value="${itemProduct.genericName}"/>",
				generalIndication:"<c:out value="${itemProduct.generalIndication}"/>",
				code:"<c:out value="${itemProduct.code}"/>",
				codeBar:"<c:out value="${itemProduct.codeBar}"/>",
				activeSubstance:activeSubstanceTemp,
				compositionCollection:listCompositionTemp,
				productattributesCollection:listProductAttributesTemp};
		productListDetail.push(p);
	</c:forEach>
	
	$(document).ready(function(){	
		var src = [
		           "ActionScript",
		           "AppleScript",
		           "Asp",
		           "BASIC",
		           "C",
		           "C++",
		           "Clojure",
		           "COBOL",
		           "ColdFusion",
		           "Erlang",
		           "Fortran",
		           "Groovy",
		           "Haskell",
		           "Java",
		           "JavaScript",
		           "Lisp",
		           "Perl",
		           "PHP",
		           "Python",
		           "Ruby",
		           "Scala",
		           "Scheme"];

		$("#auto").autocomplete({ 
		    source: function(request, response) {              
		        response($.ui.autocomplete.filter(src, request.term).slice(0, 2));
		        return false;
		    }
		});

		
		$("input#_nitCi").autocomplete({
			source : 'saleShowListClientByNitCi?nitCi='+$("#_nitCi").val(),
			delay : 10,
			minLength : 2,
			select : function(event,ui){
				$("#_client").val(ui.item.name);
				return false;
			}
		});		
		
		$("#formDetailItems").validate({
	        submitHandler: function(form) {
	        	if((document.getElementById("formDetailItems").elements.length) > 12){
	        		transactionRegisterSell();
	        	}else
	           		alert('No tiene filas registradas dentro de Items de la venta');
	        }
	    });
		
		$('#mainContainerDetailSale').on('click', '.deleteRowCarga', function () {
			$(this).parents('tr').first().remove();
			/* when we delete we have to verify that not exist a row because if exist we have to reset the array 'typesCompValuesIni' */
			if(!$("#mainContainerDetailSale tbody tr").hasClass("tr_decorado")){					    	
			    var trArray = ($(this).closest('tr').attr('id')).split("_");
				var trId = trArray[1];
				for (var i = 0; i < priceTotalList.length; i++) {
			    	if( trId == i)
			    		priceTotalList[i] = 0;
			    }
			    sumUp();
			    $('#mainContainerDetailSale thead tr').remove();
			    sellItemsOfProduct(trArray[4],trArray[2],trArray[3],3,1,trArray[5],false);
			}				
			if(!$("#mainContainerDetailSale tbody tr").hasClass("tr_decorado")){
				var html = '<tr><th width="21%" class="th_decoradoRowspan"><fmt:message key="table.product"/></th><th width="12%" class="th_decoradoRowspan"><fmt:message key="table.units"/></th><th width="12%" class="th_decoradoRowspan"><fmt:message key="table.unitPrice"/></th><th width="12%" class="th_decoradoRowspan"><fmt:message key="table.priceTotal"/></th><th width="12%" class="th_decoradoRowspan"><fmt:message key="table.discount"/></th><th width="12%" class="th_decoradoRowspan"><fmt:message key="table.total"/></th><th width="16%" class="th_decoradoRowspan" colspan="2"><fmt:message key="table.actions"/></th></tr>';
				$("#mainContainerDetailSale thead").append(html);
				//$('#mainContainerDetailSale tr:first-child').addClass('tabla_decorado');
			}
		});		
		$('#mainContainerDetailSale').on('click', '.editRowLoadDetail', function () {
			$(this).parents('tr').first();
			/* when we delete we have to verify that not exist a row because if exist we have to reset the array 'typesCompValuesIni' */			
			if(!$("#mainContainerDetailSale tbody tr").hasClass("tr_decorado")){					    	
				var trArray = ($(this).closest('tr').attr('id')).split("_");
				indexRowSelected = trArray[1];
				functionDialogShowFormItemSimple();					
			}
		});		
		// showDialogDetailItemsToSale(productId,providerId,stockId)
		$('.numbersOnly').keyup(function () {
	        if (this.value != this.value.replace(/[^0-9\.]/g, '')) {
	           this.value = this.value.replace(/[^0-9\.]/g, '');
	        }
	    });
		$('.percentage').keyup(function () {
	        if (this.value > 100)
	        	this.value = 100;
	        if (this.value < 0)
		    	this.value = 0;
	    });
		$('.calculate').keyup(function () {
			calculatePrice($("#_units").val(),$("#_unitPrice").val(),$("#_discount").val());
	    });
		
		/******calculate change*******/
		/*$('.calculateChange').keup(function (){
			calculateDiscount($("#_priceTotalGeneral").val(), $("#_cash").val());
		})*/
		
		
		$('.numberOnlyNumber').keyup(function () {
	        if (this.value != this.value.replace(/[^0-9]/g,'')) {
	           this.value = this.value.replace(/[^0-9]/g, '');
	        }
	    });
		$('.lettersOnly').keyup(function () {
	        if (this.value != this.value.replace(/[^A-Za-z\s]/g, '')) {
	           this.value = this.value.replace(/[^A-Za-z\s]/g, '');
	        }
	    });
		
		//^[0-9]*\.?[0-9]{1,2}$   //numbers with two decimal
		$('.numbersWithTwoDecimal').keyup(function () {
	        if (this.value != this.value.replace(/[^\d*.\d{2}$]/g, '')) { //    ^\d+(\.\d{1,2})?$  //  /[^0-9]/g
	           this.value = this.value.replace(/[^\d*.\d{2}$]/g, '');
	        }
	    });
		
		$("input[name='_dataTypeSale']").change(function(){
			showRadioDataTypeSale();
	    }); 		
		$("#_stock").change(function() {
			loadTableInSearchByStock($("#_stock").val());
		});			
		$("#searchName").keyup(function() {
			loadTableInSearchByName($("#searchName").val(),$("#_stock").val());
		});
		$("#searchCode").keyup(function() {
			loadTableInSearchByCode($("#searchCode").val(),$("#_stock").val());
		});
		$("#searchCodeBar").keyup(function() {
			loadTableInSearchByCodeBar($("#searchCodeBar").val(),$("#_stock").val());
		});		
		$("#dialogShowEditPharmacyProduct").dialog({autoOpen: false, height: 300, width: 500, modal: true,
			open: function(event, ui){		
				//alert('reloadingggggggggg.............');				
			},
			buttons: {
	            "Aceptar": function() {
	            	//var flag = $("#divShowDetailPharmacyProduct").valid();	                
	            },
	            Cancelar: function() { $( this ).dialog( "close" );}
			},
			close: function(){ $( this ).dialog( "close" ); }
		});	
		
		$("#dialogShowDetailProduct").dialog({autoOpen: false, height: 'auto',resizable: false, width: 500, modal: true,
			open: function(event, ui){		
				$(this)
				.dialog("widget")
				.find(".ui-dialog-titlebar").css({
					"float": "right",
					border: 0,
					padding: 0
				})
				.find(".ui-dialog-title").css({
					display: "none"
				}).end()
				.find(".ui-dialog-titlebar-close").css({
					top: 0,
					right: 0,
					margin: 0,
					"z-index": 999
				});
				$(this).css("padding", "0px");
				$(this).css("border", "none");
				$( "#tabs" ).tabs();
				$( "#tabs" ).css("border", "none");
				
				$(".showImage").html('<img src="<c:url value="/resources/images/portada/logo.png" />" width="180"/>');			
				//$("#tabs").tabs({ heightStyle: "fill" });
			},
			close: function(){ $( this ).dialog( "close" ); }
		});	
				
		$("#dialogShowDetailError").dialog({autoOpen: false, height: 300, width: 500, modal: true,
			open: function(event, ui){		
				//alert('reloadingggggggggg.............');				
			},
			buttons: {
	            "Aceptar": function() {
	            	$( this ).dialog( "close" );
	            },
	            Cancelar: function() { $( this ).dialog( "close" );}
			},
			close: function(){ $( this ).dialog( "close" ); }
		});			
		
		$("#dialogShowFormItemSimple").dialog({autoOpen: false, height: 400, width: 500, modal: true,
			open: function(event, ui){		
				//alert('reloadingggggggggg.............');
			},
			buttons: {
	            "Aceptar": function() {
	            	var flag = $("#formDialogItemSimple").valid();
	                if(flag){
	                	$("#tdUnit_"+indexRowSelected).text($("#_unitsd").val());
	                	$("#tdUnitPric_"+indexRowSelected).text($("#_unitPriced").val());
	                	$("#tdPriceTot_"+indexRowSelected).text($("#_priceTotald").val());
	                	$("#tdDiscount_"+indexRowSelected).text($("#_discountd").val());
	                	$("#tdPriTotal_"+indexRowSelected).text($("#_priceTotalWithDiscountd").text());
	                	for (var i = 0; i < priceTotalList.length; i++) {
	    					if(i == indexRowSelected){
	    						priceTotalList[i]=$("#tdPriTotal_"+indexRowSelected).text();
	    					}
	    				}
	                	sumUp();
	                	$( this ).dialog( "close" );
	                }
	            },
	            Cancelar: function() { $( this ).dialog( "close" );}
			},
			close: function(){ $( this ).dialog( "close" ); }
		});		
		
		$("#dialogShowFormBill").dialog({autoOpen: false, height: 700, width: 290,resizable: false, modal: true,
			open: function(event, ui){		
				$("#divShowFormBill").print();
			},
			buttons: {
	            "Aceptar": function() {
	            		alert("Salio la factura");
	                	$( this ).dialog( "close" );
	            		location.href = "sellProducts?_menuId="+"<c:out value="${param._menuId}"/>"+"&_subMenuId="+"<c:out value="${param._subMenuId}"/>"; 
	            },
	            Imprimir: function() { $("#divShowFormBill").print();}
			},
			close: function(){ 
				$( this ).dialog( "close" );
    			location.href = "sellProducts?_menuId="+"<c:out value="${param._menuId}"/>"+"&_subMenuId="+"<c:out value="${param._subMenuId}"/>"; 
    		}
		});		
		$("#dialogShowCredit").dialog({autoOpen: false, height: 'auto', width: 660, modal: true,
			open: function(event, ui){		
				$("#divFormCredit").html('');	
				if($("#frequencyPayment").val() != '' && $("#amountPayment").val() != ''){
					sumUpCredit(parseInt($("#amountPayment").val(),10));
	        	}
				
				$("#resTemp").hide();
			},
			buttons: {
	            "Aceptar": function() {
	            	var flag = $("#formCredit").valid();
                    if(flag){
                    	var valueTemp = $("input[name='searchTypePayment']:checked").val();                    	
                    	//$("#divFormCredit").html('');
                    	
            			if(valueTemp == 3){
            				$("#amountPayment").val($("#amountPaymentTemp").val());
                    		$("#frequencyPayment").val($("#frequencyPaymentTemp").val());
                    	}
            			$("#resTemp").clone().appendTo("#divFormCredit");
                    	//$("#divFormCredit").hide();
                    	$( this ).dialog( "close" );
                    }
	            },
	            Cancelar: function() { $( this ).dialog( "close" );}
			},
			close: function(){ $( this ).dialog( "close" ); }
		});	
		
		
		$(".mouseup").mouseup(function(){
			showProduct(); 
		});
		$(".mouseover").mouseover(function(){
			showProduct(); 
		});
		$("#searchTypeSale_1").click(function(){
			showCredit();
		});
		$("#seePayment").click(function(){
			if(productSelected != null && $("#_client").val() != null){
				$("#dialogShowCredit").load("showFormCredit?cfc=2&_nitCi="+$("#_nitCi").val(),function(){		
					openDialogModalForm("#dialogShowCredit","CREDITO",function(){
						
					});
				});
			}else
				if($("#_client").val() == null)
					alert('vacio cliente');
				else
					alert('vacio producto');
		});		
	});	
	function showCredit(){		
		$("#dialogShowCredit").load("showFormCredit?cfc=1",function(){
			openDialogModalForm("#dialogShowCredit","CREDITO",function(){
				//$("#nameError").text(nameError);
				//$("#detailError").text(detailError);
			});
		});
	}	
	
	function showError(nameError,detailError){
		$("#dialogShowDetailError").load("showDetailError",function(){
			openDialogModalForm("#dialogShowDetailError","ERROR",function(){
				$("#nameError").text(nameError);
				$("#detailError").text(detailError);
			});
		});
	}
	
	function transactionRegisterSell(){	
		$.ajax({ 
    		type: "POST",
    		url	: 'transactionRegisterSell',  //   		dataType: 'application/json; charset=UTF-8',
            data: $('#formDetailItems').serialize(),
       	    success:function(data){
       	    	functionDialogShowFormBill();
       		}, 
       		error: function(jqXHR, textStatus, errorThrown){
    			var exceptionObject = jQuery.parseJSON(jqXHR.responseText);
    		    /*
    			$('#errorModal')
    			.find('.modal-body p>strong').html(exceptionVO.clazz).end()
    			.find('.modal-body p>em').html(exceptionVO.method).end()
    			.find('.modal-body p>span').html(exceptionVO.message).end()
    			.modal('show');
    		    */
    			showError(exceptionObject.method,exceptionObject.clazz+' , '+exceptionObject.message);
    		}
       	}); 		
	}	
	function sellItemsOfProduct(stockId,_productId,_providerId,stateItemOld,stateItemNew,units,active){		
		$.ajax({ 
    		type: "GET",
    		url	: 'saleSellItemsProduct',
       	   	dataType: "json",		
            data: {stockId:stockId,_productId:_productId,_providerId:_providerId,stateItemOld:stateItemOld,stateItemNew:stateItemNew,_units:units,sUserId:sUserId},
            beforeSend:function(){
                $('#loadingDiv').css({display:'block'});
            },
       	    success:function(data){
    			productSelected = data.p;
    			productList 	= data.list;
    			arrayItemTemp	= data.listItem;
    			
    			if(productSelected.productPK.productId == productSelectedTemp.productPK.productId && productSelected.productPK.provideId == productSelectedTemp.productPK.provideId)
    				showProduct(); 
    			if(active)
    				loadDetails(productSelected);
    			//alert(1000);
    			
       		},complete:function(){
       			$('#loadingDiv').css({display:'none'});
       	    }, 
       		error: 	function(){alert('Error en request..');} }); 	
	}	
	function buttonAddToTable(){
		if($("#_stock").val() != ''){
			if(packageList.length > 0){			
				if(parseInt($("#_units").val(),10) <= parseInt($("#_itemList").text(),10)){
					productSelectedTemp = productSelected;
					sellItemsOfProduct($("#_stock").val(),productSelected.productPK.productId,productSelected.productPK.providerId,1,3,$("#_units").val(),true);
				}else{
					alert('Solo existen '+$("#_itemList").text()+' en Almacen !!!!');
					$("#_units").val($("#_itemList").text());
				}
			}else
				alert('No existe mas Item en este Stock!!!!');
		}
		else
			alert('Seleccione un Almacen');
	}
	function showRadioDataTypeSale(){		
		if(pack != null){
			var dataTypeSaleValue = parseInt($("input[name='_dataTypeSale']:checked").val(),10);
	        if(dataTypeSaleValue == 1){
	        	calculatePrice(contItem,retailItem,$("#_discount").val());
	        	if(retailItem == ''){
	        		$("#_units").val(null);	        
		        	$("#_priceTotal").val(null);
		        	$("#_priceTotalWithDiscount").text('');
	        	}
	        }else{
	        	calculatePrice(contItem,wholesaleItem,$("#_discount").val());
	        	if(wholesaleItem == ''){
	        		$("#_units").val(null);	        
		        	$("#_priceTotal").val(null);
		        	$("#_priceTotalWithDiscount").text('');
	        	}
	        }
		}
	}
	function calculatePrice(units,unitPrice,discount){		
		if(pack != null){
			$("#_unitPrice").val(unitPrice);
        	$("#_units").val(units);	     
        	$("#_priceTotal").val(parseFloat(units*unitPrice).toFixed(1));
        	if(unitPrice != '')
        		$("#_priceTotalWithDiscount").text(parseFloat(($("#_priceTotal").val())*((100-(discount))/100)).toFixed(1));
		}
	}
	
	/****function for calculate change*****/
	function restar(){		
		var m1= document.getElementById("_priceTotalGeneral").innerHTML /*Recupero el total introducido*/
		var m2 = document.getElementById("_cash").value;
		r = m1-m2;
		resp = Math.round(r * 100) / 100;
		
		document.getElementById("_change").value = resp;
	}
	function functionDialogShowEditPharmacyProduct(productId,providerId,stockId){
		$("#dialogShowEditPharmacyProduct").load("saleShowEditPharmacyProduct?_productId="+productId+"&_providerId="+providerId+"&_stockId="+stockId,function(){
			openDialogModalForm("#dialogShowEditPharmacyProduct","Modificar",null);
		});
	}
	function functionDialogShowDetailProduct(productId,providerId,stockId){
		loadProductShowed(productId,providerId);
		$("#dialogShowDetailProduct").load("saleShowDetailProduct",function(){
			openDialogModalForm("#dialogShowDetailProduct","Detalle Producto",function(){
				//alert(productSelected.name);
			});
		});
	}
	function loadProductShowed(productId,providerId){
		for (var i = 0; i < productListDetail.length; i++) {
			var obj = productListDetail[i];
			if(obj.productId == productId && obj.providerId == providerId)
				productShowed = obj;
		}
	}
	
	
	function functionDialogShowFormItemSimple(){
		$("#dialogShowFormItemSimple").load("saleShowFormItemSimple",function(){
			openDialogModalForm("#dialogShowFormItemSimple","Editar Item",function(){
				$("#_unitsd").val($("#tdUnit_"+indexRowSelected).text());
				$("#_unitPriced").val($("#tdUnitPric_"+indexRowSelected).text());
				$("#_priceTotald").val($("#tdPriceTot_"+indexRowSelected).text());
				$("#_discountd").val($("#tdDiscount_"+indexRowSelected).text());
				$("#_priceTotalWithDiscountd").text($("#tdPriTotal_"+indexRowSelected).text());
			});
		});
	}	
	function functionDialogShowFormBill(){
		$("#dialogShowFormBill").load("saleShowFormBill?_amountTotal="+$("#_priceTotalGeneral").text(),function(){
			openDialogModalForm("#dialogShowFormBill","Factura",function(){
				$("#_amountBill").text($("#_priceTotalGeneral").text());
				$("#_nameClientBill").text($("#_client").val());
				$("#_nitCiBill").text($("#_nitCi").val());
				var html = '';
				for(var i=0; i<indexRow; i++){
					if($("#tdPriTotal_"+i).text() != ''){
						html = 	'<tr class="tr_decorado">'+
								'	<td class="th_decorado" style="text-align: center">'+$("#tdName_"+i).text()+'</td>'+
								'	<td class="th_decorado" style="text-align: center">'+$("#tdUnit_"+i).text()+'</td>'+
								'	<td class="th_decorado" style="text-align: center">'+$("#tdPriTotal_"+i).text()+'</td>'+
								'</tr>';
						$("#mainContainerBill tbody").append(html);
					}
				}				    
			});
		});
	}
	
	function loadTableInSearchByCodeBar(codeBar,stockId){		
		$.ajax({ 
    		type: "GET",
    		url	: 'saleLoadTableTempByCodeBar',
       	   	dataType: "json",		
            data: {codeBar:codeBar,stockId:stockId},
       	    success:function(data){
       	    	productList = data;
       	    	loadProducts();	      	    	
       		}, 
       		error: 	function(){alert('Error en request..');} }); 	
	}
	function loadTableInSearchByCode(code,stockId){		
		$.ajax({ 
    		type: "GET",
    		url	: 'saleLoadTableTempByCode',
       	   	dataType: "json",		
            data: {code:code,stockId:stockId},
       	    success:function(data){
       	    	productList = data;
       	    	loadProducts();	      	    	
       		}, 
       		error: 	function(){alert('Error en request..');} }); 	
	}
	function loadTableInSearchByName(name,stockId){		
		$.ajax({ 
    		type: "GET",
    		url	: 'saleLoadTableTempByName',
       	   	dataType: "json",		
            data: {name:name,stockId:stockId},
       	    success:function(data){
       	    	productList = data;
       	    	loadProducts();	      	    	
       		}, 
       		error: 	function(){alert('Error en request..');} }); 	
	}	
	function loadTableInSearchByStock(stockId){		
		$.ajax({ 
    		type: "GET",
    		url	: 'saleLoadTableTempByStock',
       	   	dataType: "json",		
            data: {stockId:stockId},
       	    success:function(data){
       	    	productList = data;
       	    	loadProducts();			    	
       		}, error: function(){alert('Error en request..');} }); 	
	}	
	function loadProducts(){
		var html = "";
		$("#mainContainerSearch tbody").html("");
		if(productList.length > 0){
			var first = true;
			for(var i=0; i<productList.length; i++){
				var obj = productList[i];
				if(obj.pharmacyProduct != null){
					html = 	'<tr class="trSale productRow" id="'+obj.productPK.productId+'" rowIndex="'+i+'">'+
							'	<td class="th_decorado" style="text-align: center">'+(i+1)+'</td>'+
							'	<td class="th_decorado" style="text-align: center">'+obj.code+'</td>'+
							'	<td class="th_decorado" style="text-align: center">'+obj.name+'</td>'+
							'	<td class="th_decorado" style="text-align: center">'+obj.activeSubstanceId.name+'</td>'+
							'	<td class="th_decorado" style="text-align: center">'+(obj.pharmacyProduct != null?(obj.pharmacyProduct.packageCollection.length > 0?parseDateBol(obj.pharmacyProduct.packageCollection[0].dueDate):""):"")+'</td>'+
							'	<td class="th_decorado" style="text-align: center">'+obj.codeBar+'</td>'+
							'	<td class="th_decorado" style="text-align: center">'+(obj.pharmacyProduct != null?(obj.pharmacyProduct.packageCollection.length > 0?obj.pharmacyProduct.packageCollection[0].batchNumber:""):"")+'</td>'+
							'	<td class="td_decoradoDerecha" style="text-align: center"><div class="botonEditar"><a href="javascript:functionDialogShowEditPharmacyProduct(\''+obj.productPK.productId+'\',\''+obj.productPK.providerId+'\',\''+$("#_stock").val()+'\')"></a></div></td>'+
							'	<td class="td_decoradoDerecha" style="text-align: center"><a href="javascript:functionDialogShowDetailProduct(\''+obj.productPK.productId+'\',\''+obj.productPK.providerId+'\',\''+$("#_stock").val()+'\')">Ver</a></div></td>'+
							'</tr>';
					$("#mainContainerSearch tbody").append(html);
					if(first){
						activeRow = obj.productPK.productId+"";
						$("#"+obj.productPK.productId).toggleClass("rowSelectedHighLigth",true);
						productSelected = obj;
						showProductIntoProduct();
						first = false;	
						
						arrayItemTemp = [];
						
						showRadioDataTypeSale();
					}
				}
			}
			$(".productRow").click(function(){
				$("#"+activeRow).toggleClass("rowSelectedHighLigth",false);
				activeRow = $(this).attr("id");
				$(this).toggleClass("rowSelectedHighLigth", true);

				productSelected = productList[parseInt($(this).attr("rowIndex"),10)];
				showProductIntoProduct();

				arrayItemTemp = [];

				showRadioDataTypeSale();
			});
		}else{
			html = '<tr class="tr_decorado"><td class="td_decorado" colspan="9" style="text-align:center"><span style="color:red"><fmt:message key="show.noExistSearchProducts"/></span></td></tr>';
			$("#mainContainerSearch tbody").append(html);
		}
    	
	}	
	
	function addElementNoRepeatToArray(ar){ 
	    var active=false,v="",temp=[].concat(ar),r=Array(); 
	    for (var i in temp){ // 
	        v=temp[i]; 
	        active=false; 
	        for (var a in temp){ 
	            if (v==temp[a]){ 
	                if (active==false)
	                	active=true; 
	                else
	                	temp[a]=""; 
	            } 
	        } 
	    } 
	    for (var a in temp){ 
	        if (temp[a]!=""){ 
	            r.push(temp[a]); 
	        } 
	    } 
	    return r; 
	}
	
	
	function loadDetails(obj){			
		var arrayTemp = [];
		var stringElement = '';		
		var listTemp = [];
		for (var i = 0; i < arrayItemTemp.length; i++) {
			arrayTemp.push(arrayItemTemp[i].itemPK.packageId);
		}		
		listTemp = addElementNoRepeatToArray(arrayTemp);
		for (var i = 0; i < listTemp.length; i++) {
			stringElement = stringElement+listTemp[i];
			if ((listTemp.length-1) != i) {
				stringElement = stringElement+'**';
			}
		} 
		//alert(stringElement);				 
		var htmlTemp = "";
		if(obj != null){			
			htmlTemp =	'<tr class="tr_decorado" id="trDetails_'+indexRow+'_'+obj.productPK.productId+'_'+obj.productPK.providerId+'_'+$("#_stock").val()+'_'+$("#_units").val()+'" >'+			
						'	<td class="th_decorado" id="tdName_'+indexRow+'" style="text-align: center">'+obj.name+'</td>'+
						'	<td class="th_decorado" id="tdUnit_'+indexRow+'" style="text-align: center">'+$("#_units").val()+'</td>'+
						'	<td class="th_decorado" id="tdUnitPric_'+indexRow+'" style="text-align: center">'+$("#_unitPrice").val()+'</td>'+
						'	<td class="th_decorado" id="tdPriceTot_'+indexRow+'" style="text-align: center">'+$("#_priceTotal").val()+'</td>'+
						'	<td class="th_decorado" id="tdDiscount_'+indexRow+'" style="text-align: center">'+$("#_discount").val()+'</td>'+
						'	<td class="th_decorado" id="tdPriTotal_'+indexRow+'" style="text-align: center">'+$("#_priceTotalWithDiscount").text()+'</td>'+
						'	<td class="th_decorado" style="text-align: center"><div class="botonEditar"><a href="#" class="editRowLoadDetail"></a></div></td>'+
						'	<td class="th_decorado" style="text-align: right"><div class="botonEliminar"><a href="#" class="deleteRowCarga"></a></div></td>'+
	        			'	<input type="hidden" name="dp_'+indexRow+'" id="dp_'+indexRow+'_'+obj.productPK.productId+'_'+obj.productPK.providerId+'_'+$("#_stock").val()+'_'+$("#_units").val()+'"  value="dp_'+indexRow+'_'+obj.productPK.productId+'_'+obj.productPK.providerId+'_'+$("#_stock").val()+'_'+$("#_units").val()+'_'+$("#_priceTotalWithDiscount").text()+'||'+stringElement+'" />'+
						'</tr>';
	    	priceTotalList.push($("#_priceTotalWithDiscount").text());
			$("#mainContainerDetailSale tbody").after(htmlTemp);
			//$('#mainContainerDetailSale tr:first-child').addClass('tabla_decorado');			
			//$('#mainContainerDetailSale thead tr').addClass('tabla_decorado');
			//$('#mainContainerDetailSale tr:first-child').addClass('tabla_decorado');
			sumUp();
			indexRow++;
	        $("#indexRowDetailItems").val(indexRow);
		}
	}	
	function sumUp(){
		var item = 0.0;
		var itemLit=''; 
		var itemCam=0.0;
		var itemEfe=0.0;
		for (var j = 0; j < priceTotalList.length; j++) {
			if(priceTotalList[j] != null)
				item = parseFloat(parseFloat(item) + parseFloat(priceTotalList[j])).toFixed(2);
		}		
		$("#_priceTotalGeneral").text(item);
		
		var valor=document.getElementById("_priceTotalGeneral".value);
	
	    var mensaje= document.getElementById("_priceTotalGeneral").innerHTML /*Recupero el total introducido*/
	    
		textLiteral= covertirNumLetras(mensaje);/*lo comvierto en texto*/  //getFormatoLiteral
		//textLiteral= getFormatoLiteral(mensaje);  /*Con lo que hay de andres en el common.js*/
		
		$("#_priceTotalLiteral").text(textLiteral);
		var valorLit=document.getElementById("_priceTotalLiteral".value);
		
		var cash = document.getElementById("_cash");
		cash.value=mensaje;
		
		var menEfe= document.getElementById("_cash").value; /*Recupero el dato introducido*/
		itemCam=mensaje-menEfe;
		
		var change= document.getElementById("_change");
		change.value=itemCam;
	}	
	function loadShowProduct(){		
		contItem 	= 0;
		countPackage= 0;
		pack 		= null;
		packageList = [];
		itemList 	= [];		
		
		var disponible	= 0;
		var proceso 	= 0;
		var vendido 	= 0;
		var procesoOtro = 0;


		for (var i = 0; i < productSelected.pharmacyProduct.packageCollection.length; i++) {
			var objPackage = productSelected.pharmacyProduct.packageCollection[i];
			pack = productSelected.pharmacyProduct.packageCollection[i];
			var activeStateOne = false;
			for (var j = 0; j < objPackage.itemCollection.length; j++) {
				var objItem = objPackage.itemCollection[j];
				if(objItem.stockId.stockId == $("#_stock").val()){
					if(parseInt(objItem.state,10) == 1){
						contItem++;
						activeStateOne=true;
						itemList.push(objItem);
						disponible++;
					}
					if(parseInt(objItem.state,10) == 2){
						vendido++;
					}
					if(parseInt(objItem.state,10) == 3){
						if(parseInt(objItem.tempState,10) == parseInt(sUserId,10))
							proceso++;
						else
							procesoOtro++;
					}
				}
			}
			if(activeStateOne){
				packageList.push(pack);
				countPackage++;
			}
		}	
		
		retailPackage 	= ((contItem != 0)?(pack.tempTotal1 != null)?parseFloat(pack.tempTotal1/countPackage).toFixed(1):'0':'');
		retailItem 		= ((contItem != 0)?(pack.tempTotal1 != null)?parseFloat(pack.tempTotal1/contItem).toFixed(1):'0':'');
		
		wholesaleItem 	= ((contItem != 0)?(pack.tempTotal2 != null)?parseFloat(pack.tempTotal2/contItem).toFixed(1):'0':'');
		wholesalePackage= ((contItem != 0)?(pack.tempTotal2 != null)?parseFloat(pack.tempTotal2/countPackage).toFixed(1):'0':'');
		
		var html='';
		
		html +=	'<table style="width: 100%">'+
				'	<tr>'+
				'		<td>'+													
				'			&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#60be00;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>&nbsp;&nbsp;<fmt:message key="form.available"/>:<span id="p_available">'+disponible+'</span>'+	
				'			&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#f70303;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>&nbsp;&nbsp;<fmt:message key="form.sold"/>:<span id="p_sold">'+vendido+'</span>'+									
				'			&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#f4f402;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>&nbsp;&nbsp;<fmt:message key="form.process"/>:<span id="p_process">'+proceso+'</span>'+	
				'			&nbsp;&nbsp;&nbsp;&nbsp;<span style="background:#76c8f6;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>&nbsp;&nbsp;<fmt:message key="form.processByAnother"/>:<span id="p_process_by_another">'+procesoOtro+'</span><br/>'+
				'		</td>'+
				'	</tr>'+
				'</table>';
		html +=	'<table style="width: 100%">'+
				'	<tr>'+
				'		<td>'+
				'			<label>1 paquete contiene '+((productSelected.pharmacyProduct != null)?productSelected.pharmacyProduct.valueTempCountItem:'0')+' Unidades</label><br/>'+
				'			<label><fmt:message key="form.packageInStock"/>: <b id="_packageList"> '+packageList.length+' </b></label>  <label><fmt:message key="form.unitsInStock"/>: <b id="_itemList">'+itemList.length+'</b></label>'+
				'		</td>'+
				'	</tr>'+
				'	<tr>'+
				'		<td>'+
				'			<table class="tabla_decorado" style="width: 100%">'+
				'				<thead>'+
				'					<tr>'+
				'						<th width="26%" class="th_decoradoRowspan"><fmt:message key="table.type"/></th>'+
				'						<th width="37%" class="th_decoradoRowspan"><fmt:message key="table.salePriceByUnit"/></th>'+
				'						<th width="37%" class="th_decoradoRowspan"><fmt:message key="table.salePriceByPackage"/></th>'+
				'					</tr>'+
				'				</thead>'+				
				'				<tbody>'+
				'						<tr class="tr_decorado">'+
				'							<td class="th_decorado" style="text-align: center"><fmt:message key="form.retail"/></td>'+
				'							<td class="th_decorado" style="text-align: center">'+retailItem+'</td>'+
				'							<td class="th_decorado" style="text-align: center">'+retailPackage+'</td>'+
				'						</tr>'+
				'						<tr class="tr_decorado">'+
				'							<td class="th_decorado" style="text-align: center"><fmt:message key="form.wholesale"/></td>'+
				'							<td class="th_decorado" style="text-align: center">'+wholesaleItem+'</td>'+
				'							<td class="th_decorado" style="text-align: center">'+wholesalePackage+'</td>'+
				'						</tr>'+
				'				</tbody>'+				
				'			</table>'+														
				'		</td>'+
				'	</tr>'+
				'</table>'+ 
				'<table style="width: 100%">'+
				'	<tr>'+
				'		<td>'+
				'			<div style="clear:both;">'+
				'				<label><b><fmt:message key="form.provider"/>:</b> '+productSelected.provider.name+' </label><br/>'+	
				'				<label><b><fmt:message key="form.productName2"/>:</b> '+productSelected.name+' </label><br/>'+	
				'				<label><b><fmt:message key="form.activePrinciple"/>:</b> '+productSelected.activeSubstanceId.name+' </label><br/>'+	
				'				<label><b><fmt:message key="form.therapeuticAction"/>:</b> '+productSelected.activeSubstanceId.therapeuticAction+' </label><br/>'+	
				'				<label><b><fmt:message key="form.location"/>:</b> '+(productSelected.pharmacyProduct !== null?productSelected.provider.address!=null?productSelected.provider.address:'Sin ubicaci&oacute;n':'')+' </label><br/><br/>'+
				'			</div>'+										
				'		</td>'+
				'		<td>'+
				'			Imagen'+
				'		</td>'+
				'	</tr>'+
				'	<tr>'+
				'		<td>'+
				'			<div style="clear:both;">'+
				'				<label class="${classTemp}"><fmt:message key="form.requiresPrescription"/> :</label>'+
				'				<input type="radio" name="_requiresPrescription" id="requiresPrescription_1" value="1" class="required " checked="checked"/><label for="requiresPrescription_1">&nbsp;<fmt:message key="form.yes"/>&nbsp;&nbsp;</label>'+
				'				<input type="radio" name="_requiresPrescription" id="requiresPrescription_0" value="0" class="required " /><label for="requiresPrescription_0">&nbsp;<fmt:message key="form.no"/>&nbsp;&nbsp;</label>'+
				'			</div>'+
				'		</td>'+
				'		<td>'+
				'			<div style="clear:both;">'+
				'				<a style="margin: 1em 0; display: block;color: #CC0000;text-decoration: underline;" href=""><fmt:message key="form.detailProduct"/></a>'+
				'			</div>'+
				'		</td>'+
				'	</tr>'+
				'</table>';		
		$("#mainShowDataProducts").html(html);
	}
	function showProduct(){
		if(productSelected != null){
			var providerId= productSelected.productPK.providerId;
			var productId = productSelected.productPK.productId;
			$.ajax({ 
	    		type: "GET",
	    		url	: 'saleLoadProductSelected',
	       	   	dataType: "json",		
	            data: {_providerId:providerId,_productId:productId,stockId:$("#_stock").val()},
	       	    success:function(data){
	       	    	productSelected = data;
	       	    	loadShowProduct();	      	    	
	       		}, 
	       		error: 	function(){alert('Error en request..');} }); 	
		}	
	}
	function showProductIntoProduct(){
		if(productSelected != null){
			var providerId= productSelected.productPK.providerId;
			var productId = productSelected.productPK.productId;
			$.ajax({ 
	    		type: "GET",
	    		url	: 'saleLoadProductSelected',
	       	   	dataType: "json",		
	            data: {_providerId:providerId,_productId:productId,stockId:$("#_stock").val()},
	       	    success:function(data){
	       	    	productSelected = data;
	       	    	loadShowProduct();	      	    	
	       		},complete:function(){
	    			showRadioDataTypeSale();
	       	    }, 
	       		error: 	function(){alert('Error en request..');} }); 	
		}	
	}
	
		
	
</script>
</head>

<body>
<div id="top-wrap">
	<%@include file="../../head.jsp"  %>
	<div id="bodySpace">
		
	    <div class="clearfix" id="middle" style="position: absolute">  <!-- aqui va la ruta -->
	        <!-- aqui va el arbol de entrada -->
	        <div id="breadcrumb">
	            <ul>
                	<li><a href="<spring:url value="/mainFront?" htmlEscape="true" />">Home</a></li>	
                    <li><span style="color:#666"><fmt:message key="title.transactions"/></span></li>
                    <li class="current-page"><span class="end"><span class="middle"><fmt:message key="title.saleProducts"/></span></span></li>
                </ul>
	        </div>
	    </div>
	    
	    <div id="principal">
            <!-- izquierda -->
            <div class="cuerpo2y" style="border: 0px solid"><br/><br/><!-- estos break son necesarios ya q uso absolute en css  cuerpo izquierdo-->
                <div class="izq">
					<%-- <%@include file="../../bodyIzq.jsp" %>	 --%>
                </div>
                <div class="der" style="border: 0px solid">
					<h2 class="decorado"><fmt:message key="title.saleProducts"/></h2></br></br> 					
					<div id="loadingDiv" class="loading" style="display: none;">
						<div id="imgLoad" style="float: left;width: 100%;"><img src="<c:url value="/resources/images/imgLoad/ajax-loader.gif" />" width="32" height="32" alt="ajax-loader.gif" style="position:absolute; top:30%; left:50%;"/></div> 
					</div>										
					<div id="dialogShowEditPharmacyProduct"></div> 
					<div id="dialogShowFormItemSimple"></div>
					<div id="dialogShowFormBill"></div>	
					<div id="dialogShowDetailError"></div>			
					
					<div id="dialogShowDetailProduct"></div> 	
																							
					<div id="sale">
						<table style="width:100%;float:left;table-layout:fixed;">
							<tr>
								<td width="60%">
									<fieldset class="fieldset1">		
										<legend class="legend1"><fmt:message key="title.search"/></legend>
										<table style="width: 100%">
											<tr>
												<td> 
													<select name="_stock" id="_stock"  title="<fmt:message key="show.form.selected.stock"/>">
														<option value=""><fmt:message key="form.stock"/></option>
														<c:forEach var="item" items="${listPharmacyStock}">
															<option value="${item.pharmacystockPK.stockId}">${item.stock.name}</option>
														</c:forEach> 
													</select>
													&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
													<label for="_searchByList" ><b><fmt:message key="form.searchBy"/> :</b></label>					
													<select name="_searchByList" id="_searchByList"  title="<fmt:message key="show.form.default"/>">
														<option value=""><fmt:message key="form.selected"/></option>
														<option value="1"><fmt:message key="title.productName"/></option>
														<option value="2"><fmt:message key="title.activePrinciple"/></option>
														<option value="3"><fmt:message key="title.therapeuticAction"/></option>
													</select>
													&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
													<input type="text" id="searchName" class="lettersOnly" style="border:1px solid #959595; margin-left:0.2em;" placeholder="<fmt:message key="form.productName"/>">
													<input type="text" id="searchCode" class="numbersOnly" style="border:1px solid #959595; margin-left:0.2em;" placeholder="<fmt:message key="form.code"/>">	
													<input type="text" id="searchCodeBar" class="numbersOnly" style="border:1px solid #959595; margin-left:0.2em;" placeholder="<fmt:message key="form.codeBar"/>">	
												</td>
											</tr>
											<tr>
												<td> 					
													<div id="mainContainerSearchDiv" style="width:100%;height:140px;overflow:auto;" >
														<table class="tabla_decorado" id="mainContainerSearch" style="width: 100%">
															<thead><tr><th width="3%" class="th_decoradoRowspan"><fmt:message key="table.num"/></th><th width="15%" class="th_decoradoRowspan"><fmt:message key="table.code"/></th><th width="20%" class="th_decoradoRowspan"><fmt:message key="table.nameProduct"/></th><th width="10%" class="th_decoradoRowspan"><fmt:message key="table.activePrinciple"/></th><th width="9%" class="th_decoradoRowspan"><fmt:message key="table.fVcto"/></th><th width="9%" class="th_decoradoRowspan"><fmt:message key="table.codBar"/></th><th width="9%" class="th_decoradoRowspan"><fmt:message key="table.batch"/></th><th width="7%" colspan="2" class="th_decoradoRowspan"></th></tr></thead>
															<tbody></tbody>
														</table>
													</div>							
												</td>
											</tr>
										</table>										
										<br/><br/>
									</fieldset>			
								</td>
								<td width="40%">
									<fieldset class="fieldset1">		
										<legend class="legend1"><fmt:message key="title.dataProducts"/></legend>
										<div id="mainShowDataProducts"></div>
										<br/><br/>
									</fieldset>	
								</td>
							</tr>
						</table>	
						<table style="width:100%;float:left;table-layout:fixed;">
							<tr>
								<td width="30%">
									<div style="clear:both;">
										<fieldset class="fieldset2">		
											<legend class="legend2"><fmt:message key="title.dataSale"/></legend>
											&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;									
											<div style="clear:both;">
												<label class="${classTemp}"><fmt:message key="form.typeSale"/> :</label>		
												<input type="radio" name="_dataTypeSale" id="_dataTypeSale_1" value="1" class="required" checked="checked"/><label for="_dataTypeSale_1">&nbsp;<fmt:message key="form.retail"/>&nbsp;&nbsp;</label>
												<input type="radio" name="_dataTypeSale" id="_dataTypeSale_0" value="0" class="required" /><label for="_dataTypeSale_0">&nbsp;<fmt:message key="form.wholesale"/>&nbsp;&nbsp;</label>
											</div>											
											<div style="clear:both;">
												<c:set var="showUnitPrice" scope="page"><fmt:message key="show.form.unitPrice"/>.</c:set>																																				                             												
												<label class="${classTemp}"><fmt:message key="form.unitPrice"/>:</label>
												<input type="text" name="_unitPrice" id="_unitPrice"  value="" class="required form_input_align numbersOnly calculate" title="${showUnitPrice}" placeholder="números"/>&nbsp;&nbsp;<fmt:message key="title.sigleMoney"/>
											</div>											
											<div style="clear:both;">
												<c:set var="showUnits" scope="page"><fmt:message key="show.form.units"/>.</c:set>																																				                             												
												<label class="${classTemp}"><fmt:message key="form.units"/>: </label>
												<input type="text" name="_units" id="_units"  value="" class="required form_input_align numberOnlyNumber calculate" title="${showUnits}" placeholder="números"/>
											</div>										
											<div style="clear:both;">
												<c:set var="showPriceTotal" scope="page"><fmt:message key="show.form.priceTotal"/>.</c:set>																																				                             												
												<label class="${classTemp}"><fmt:message key="form.priceTotal"/>: </label>
												<input type="text" name="_priceTotal" id="_priceTotal"  value="" class="required form_input_align numbersOnly calculate" title="${showPriceTotal}" placeholder="números"/>&nbsp;&nbsp;<fmt:message key="title.sigleMoney"/>
											</div>	
											<div style="clear:both;">
												<c:set var="showDiscount" scope="page"><fmt:message key="show.form.discount"/>.</c:set>																																				                             												
												<label class="${classTemp}"><fmt:message key="form.discount"/>:</label>
												<input type="text" name="_discount" id="_discount" value="0" class="form_input_align numbersOnly percentage calculate" title="${showDiscount}" placeholder="números"/> &nbsp;&nbsp;%
											</div>
											<div style="clear:both;">
												<label class="${classTemp}"><fmt:message key="form.priceTotalEachDesc"/>:</label>
												<label ><div id="_priceTotalWithDiscount"></div></label>
											</div>
											&nbsp;&nbsp;
											<div style="clear: both">
												<label class="form_align40">&nbsp;</label>
												<input type="button" value="<fmt:message key="button.add"/> <fmt:message key="title.product"/>" onclick="buttonAddToTable()" class="mouseover boton" title="<fmt:message key="onclick.add"/> <fmt:message key="title.product"/>."/>
											</div>
										</fieldset>	
									</div>		
								</td>
								<td width="70%">
									<fieldset class="fieldset2">		
										<legend class="legend2"><fmt:message key="title.detailItemsOfSale"/></legend>
										<form id="formDetailItems">
											<div id="dialogShowCredit"></div> 
											<div id="divFormCredit"></div> 
											<div>
												<input type="hidden" name="pharmacyId" value="${s_UserPharmacy.userpharmacyPK.pharmacyId}"/>       
												<input type="hidden" name="userId" value="${s_UserPharmacy.userpharmacyPK.userId}"/>       
												
												<label><fmt:message key="form.typeSale"/> :</label>		
												<input type="radio" name="searchTypeSale" id="searchTypeSale_0" value="0" class="required " checked="checked" /><label for="searchTypeSale_0">&nbsp;&nbsp;<fmt:message key="form.forCash"/> &nbsp;&nbsp;&nbsp;&nbsp;</label>
								    			<input type="radio" name="searchTypeSale" id="searchTypeSale_1" value="1" class="required " /><label for="searchTypeSale_1">&nbsp;&nbsp;<fmt:message key="form.onCredit"/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
												<input type="button" value="ver pagos" id="seePayment" class="boton" title="ver pagos"/>
												&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
												<label><fmt:message key="form.nitCi"/> :</label>		
												<input type="text" name="_nitCi" id="_nitCi" class="required numberOnlyNumber" style="border:1px solid #959595; margin-left:0.2em;" title="ingrese CI nit" placeholder="números">
												&nbsp;&nbsp;
												<label><fmt:message key="form.client"/> :</label>		
												<input type="text" name="_client" id="_client" class="required lettersOnly" style="border:1px solid #959595; margin-left:0.2em;" title="ingrese cliente" placeholder="letras">
												&nbsp;&nbsp;	
											</div>
											&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
										
											<input type="hidden" name="indexRowDetailItems" id="indexRowDetailItems" value="0" />
											<div style="width:100%;height:80px;overflow:auto;" >												
												<table class="tabla_decorado" id="mainContainerDetailSale" style="width: 100%">
													<thead><tr class="tr_decorado"><th width="21%" class="th_decoradoRowspan"><fmt:message key="table.product"/></th><th width="12%" class="th_decoradoRowspan"><fmt:message key="table.units"/></th><th width="12%" class="th_decoradoRowspan"><fmt:message key="table.unitPrice"/></th><th width="12%" class="th_decoradoRowspan"><fmt:message key="table.priceTotal"/></th><th width="12%" class="th_decoradoRowspan"><fmt:message key="table.discount"/></th><th width="12%" class="th_decoradoRowspan"><fmt:message key="table.total"/></th><th width="16%" class="th_decoradoRowspan" colspan="2"><fmt:message key="table.actions"/></th></tr></thead>
													<tbody></tbody>
												</table>
											</div>
											<div>
												<table class="tabla_decorado" id="mainContainerDetailSale2" style="width: 100%">
													<tbody>
														<tr class='tr_decorado'>
															<td class='td_decorado' colspan="6"><label><fmt:message key="show.are"/>: <b id="_priceTotalLiteral"></b></label></td>
															<td class='td_decorado' colspan="2" align="right">
															<label><fmt:message key="show.total"/>:  <b id="_priceTotalGeneral"></b>  </label>
															</td>
														</tr>
													</tbody>
												</table>
											</div>
											&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
											<div>
												<table style="width: 100%">
													<tr>
														<td width="40%">
															<label><fmt:message key="form.observations"/> :</label>		
															<input type="text" name="_observations" id="_observations" class="" style="border:1px solid #959595; margin-left:0.2em;" placeholder="texto">
														</td>
														<td width="60%">
															<fieldset>
																<legend><fmt:message key="title.detailItemsOfSale"/></legend>	
																<div style="clear: both">																
																	<label class="${classTemp}"><fmt:message key="form.cash"/> :</label>
																	<input type="text" name="_cash" id="_cash" class="numbersWithTwoDecimal" style="border:1px solid #959595; margin-left:0.2em;" onchange=" 
																	restar(); range = /^\d{1,4}(\.\d{1,2})?$/;
																	hundred = /^10000$/;
																	if(!(range.test(this.value) || hundred.test(this.value)))alert('Ingrese un número en Efectivo con dos decimales en un rango de 0 a 10000');
																	" placeholder="números">
																</div>
																<div style="clear: both">																
																	<label class="${classTemp}"><fmt:message key="form.change"/> :</label>		
																	<input type="text" name="_change" id="_change" class="numbersWithTwoDecimal" style="border:1px solid #959595; margin-left:0.2em;" placeholder="números">
																	<label>Imgen Flecha</label>
																</div>
																<div style="clear: both">
																	<label class="${classTemp}"></label>
																	<input type="submit" value="<fmt:message key="button.register"/> <fmt:message key="title.sale"/>" class="boton" title="<fmt:message key="onclick.register"/> <fmt:message key="title.sale"/>."/>
																	&nbsp;&nbsp;&nbsp;&nbsp;
																	<input type="button" value="<fmt:message key="button.cancel"/>" class="boton" title="<fmt:message key="onclick.cancel"/> <fmt:message key="title.sale"/>."/>
																</div>
															</fieldset>	
														</td>
													</tr> 
												</table>
											</div>
										</form>
									</fieldset>	
								</td>
							</tr>
						</table>					
					</div>	                                
                </div>
            </div><!--end of leftPan-->
            
            <div class="yDer" style="border: 1px solid #ccc;">
                  <%@include file="../../notices.jsp" %>                       
            </div><!--end of rightPan-->
        </div><!--end main content -->
	</div>
</div>
</body>
</html>
